<template>
  <div data-vjs-player style="width: 100%; height: 100%;">
    <div class="flex-c" style="width: 100%; height: 100%;">
      <!-- vue-video-crop -->
      <video
        ref="videoNode"
        style="margin: 0 auto;width: 100%; height: 100%;"
        crossorigin="anonymous"
        class="video-js vjs-default-skin vjs-big-play-centered"
      >
        抱歉，您的浏览器不支持
      </video>
    </div>
  </div>
</template>

<script>
import videojs from 'video.js'
// 播放器中文，不能使用.js文件
import videozhCN from 'video.js/dist/lang/zh-CN.json'
// 样式文件注意要加上
import 'video.js/dist/video-js.css'
export default {
  props: {
    width: {
      type: String,
      default: '650px'
    },
    height: {
      type: String,
      default: '500px'
    },
    url: {
      type: String,
      default:
        'https://cesium.com/public/SandcastleSampleData/big-buck-bunny_trailer.mp4'
    },
    autoplay: {
      type: Boolean,
      default: true
    },
    controls: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      player: null,
      options: {
        autoplay: true, // 自动播放
        language: 'zh-CN',
        controls: this.controls, // 控制条
        preload: 'auto', // 自动加载
        errorDisplay: true, // 错误展示
        // fluid: true, // 跟随外层容器变化大小，跟随的是外层宽度
        width: this.width,
        height: this.height,
        controlBar: this.controls, // 设为false不渲染控制条DOM元素，只设置controls为false虽然不展示，但是存在
        // textTrackDisplay: false,  // 不渲染字幕相关DOM
        notSupportedMessage: '此视频暂无法播放，请稍后再试',
        sources: [
          {
            src: this.url, // 视频或者直播地址
            type: 'video/mp4'
          }
        ]
      }
    }
  },
  watch: {
    url(val) {
      if (val) {
        this.$nextTick(() => {
          this.open()
        })
      }
    }
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose()
    }
  },
  // 初始化播放器
  mounted() {
    this.open()
  },
  methods: {
    open() {
      this.close()
      this.options.autoplay = this.autoplay
      this.options.controls = this.controls
      this.options.controlBar = this.controls
      // this.options.sources[0].src = `https://cesium.com/public/SandcastleSampleData/big-buck-bunny_trailer.mp4`
      this.options.sources[0].src = this.url
      this.player = videojs(
        this.$refs.videoNode,
        this.options
      )
      console.log(this.options)
      videojs.addLanguage('zh-CN', videozhCN)
    },
    close() {
      if (this.player) {
        this.player.dispose()
      }
    }
  }
}
</script>
